import { useCallback } from "react";

/**
 * 复制文本到剪贴板
 *
 * @param {Function} callback 回调函数
 * @returns Function
 */
const useClipboardCopy = (callback) => {
  const handleCallBack = useCallback((res) => callback && callback(res), [callback]);

  const copyToClipboard = useCallback(
    (text) => {
      if (navigator.clipboard) {
        navigator.clipboard
          .writeText(text)
          .then(() => handleCallBack({ status: true, text: "复制成功：" + text }))
          .catch((error) => Promise.reject(error));
      } else {
        return Promise.reject(new TypeError("navigator.clipboard is not defined"));
      }
    },
    [handleCallBack]
  );

  return copyToClipboard;
};
export default useClipboardCopy;
